<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色名称</el-breadcrumb-item>
      <el-breadcrumb-item>角色表述</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-button
        class="add_roles"
        type="primary"
        @click="addRolesVisible = true"
        >添加角色</el-button
      >
      <!-- 添加用户弹窗 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRolesVisible"
        width="30%"
        @close="closeAddRolesDialog"
      >
        <el-form ref="addRolesFormRef" :model="addRolesForm" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addRolesVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 列表数据显示区域 -->
      <el-table :data="rolesList" stripe style="width: 100%" border>
        <!-- 展开列 -->
        <el-table-column type="expand" label="展开" align="center" width="50px">
          <template v-slot="scope">
            <!-- <pre>{{ scope.row.id }}</pre> -->
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              class="bdbottom vcenter"
              :class="{ bdtop: i1 === 0 ? true : false }"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="success"
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二，三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  class="vcenter"
                  :class="{ bdtop: i2 === 0 ? false : true }"
                >
                  <el-col :span="6">
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="primary"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" align="center">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-setting"
              >设置</el-button
            >
            <el-button size="mini" type="warning" icon="el-icon-delete"
              >删除</el-button
            ><el-button
              size="mini"
              type="danger"
              icon="el-icon-search"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 点击分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="30%"
      @close="setRightDialogclosed"
    >
      <el-tree
        :data="rightsList"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        :props="treeProps"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import {
  reqRoles,
  reqAddRoles,
  reqRemoveRolesRights,
  reqAllRights,
  reqAllotRights,
} from "../../api";
export default {
  data() {
    return {
      // 权限角色列表
      rolesList: [],
      // 点击按钮，展示添加角色弹窗
      addRolesVisible: false,
      // 添加角色的表单
      addRolesForm: {},
      // 是否展示分配权限对话框
      setRightDialogVisible: false,
      //权限列表
      rightsList: [],
      // 树型控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 默认选中三级权限的id
      defKeys: [],
      // 当前角色的id
      roleId: "",
    };
  },
  mounted() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const result = await reqRoles();
      if (result.meta.status != 200)
        return this.$message.error(result.meta.msg);
      else {
        this.rolesList = result.data;
        console.log(result.data);
      }
    },
    // 添加角色
    async addRoles() {
      const result = await reqAddRoles(this.addRolesForm);
      if (result.meta.status != 201)
        return this.$message.error(result.meta.msg);
      else {
        this.addRolesForm = result.data;
        this.$message.success(result.meta.msg);
        // 隐藏添加角色弹框
        this.addRolesVisible = false;
        // 重新获取roles页面数据
        this.getRolesList();
      }
    },

    // 关闭弹窗清除表单内容
    closeAddRolesDialog() {
      this.$refs.addRolesFormRef.resetFields();
    },

    // 根据id值删除对应的角色指定权限
    removeRightById(role, id) {
      this.$confirm("此操作将永久该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const roleId = role.id;
          const rightId = id;
          const result = await reqRemoveRolesRights({ roleId, rightId });
          if (result.meta.status != 200)
            return this.$message.error(result.meta.msg);
          else {
            // 更新当前角色下最新的权限数据，不用再次调用this.getRolesList()更新了
            role.children = result.data;
            this.$message.success(result.meta.msg);
          }
        })
        .catch(() => {});
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      // 当前角色的id
      this.roleId = role.id;
      // 获取所以权限信息
      const result = await reqAllRights();
      if (result.meta.status != 200)
        return this.$message.error(result.meta.msg);
      else {
        // 获取到的权限数据保存到rightsList中
        this.rightsList = result.data;

        this.getLeafKeys(role, this.defKeys);
        console.log(this.defKeys);
        this.setRightDialogVisible = true;
      }
    },
    // 通过递归获取三级权限的id
    getLeafKeys(node, arr) {
      if (!node.children) {
        // 没有children就是三级权限
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 监听分配权限对话框关闭事件
    setRightDialogclosed() {
      //
      this.defKeys = [];
    },
    // 点击为角色分配权限  添加分配
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const result = await reqAllotRights(this.roleId, idStr);
      if (result.meta.status !== 200)
        return this.$message.error(result.meta.msg);
      this.$message.success(result.meta.msg);
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}
.add_roles {
  margin-bottom: 20px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 10px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>